/**
 * 对象存储接口工具
 * 用于向对象存储服务请求资源
 */

const config = {
  externalEndpoint: 'https://objectstorageapi.bja.sealos.run',
  bucketName: 'a0qepsyj-001'
};

/**
 * 获取对象URL
 * @param {string} objectKey - 对象键
 * @returns {string} - 完整的对象URL
 */
function getObjectURL(objectKey) {
  try {
    const encodedPath = encodeURIComponent(objectKey).replace(/%2F/g, '/');
    return `${config.externalEndpoint}/${config.bucketName}/${encodedPath}`;
  } catch (error) {
    console.error('生成URL失败:', error);
    return '';
  }
}

/**
 * 上传文件到对象存储
 * @param {string} filePath - 本地文件路径
 * @param {string} objectKey - 目标对象键
 * @returns {Promise} - 上传结果Promise
 */
function uploadFile(filePath, objectKey, contentType = 'application/octet-stream') {
  return new Promise((resolve, reject) => {
    const encodedPath = encodeURIComponent(objectKey).replace(/%2F/g, '/');
    const url = `${config.externalEndpoint}/${config.bucketName}/${encodedPath}`;
    
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: 'file',
      header: {
        'Content-Type': contentType
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve({
            statusCode: res.statusCode,
            objectKey: objectKey,
            url: url
          });
        } else {
          reject(new Error(`上传失败: HTTP ${res.statusCode}`));
        }
      },
      fail: (error) => {
        reject(error);
      }
    });
  });
}

/**
 * 从对象存储下载文件
 * @param {string} objectKey - 对象键
 * @param {string} savePath - 保存路径
 * @returns {Promise} - 下载结果Promise
 */
function downloadFile(objectKey, savePath) {
  return new Promise((resolve, reject) => {
    const url = getObjectURL(objectKey);
    
    wx.downloadFile({
      url: url,
      filePath: savePath,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve({
            statusCode: res.statusCode,
            tempFilePath: res.tempFilePath,
            filePath: savePath
          });
        } else {
          reject(new Error(`下载失败: HTTP ${res.statusCode}`));
        }
      },
      fail: (error) => {
        reject(error);
      }
    });
  });
}

/**
 * 获取对象信息
 * @param {string} objectKey - 对象键
 * @returns {Promise} - 对象信息Promise
 */
function getObjectInfo(objectKey) {
  return new Promise((resolve, reject) => {
    const url = getObjectURL(objectKey);
    
    wx.request({
      url: url,
      method: 'HEAD',
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve({
            statusCode: res.statusCode,
            objectKey: objectKey,
            metadata: res.header,
            contentLength: parseInt(res.header['content-length'] || '0'),
            contentType: res.header['content-type'],
            etag: res.header['etag']
          });
        } else if (res.statusCode === 404) {
          reject(new Error(`对象不存在: ${objectKey}`));
        } else {
          reject(new Error(`获取对象信息失败: HTTP ${res.statusCode}`));
        }
      },
      fail: (error) => {
        reject(error);
      }
    });
  });
}

/**
 * 删除对象
 * @param {string} objectKey - 对象键
 * @returns {Promise} - 删除结果Promise
 */
function deleteObject(objectKey) {
  return new Promise((resolve, reject) => {
    const url = getObjectURL(objectKey);
    
    wx.request({
      url: url,
      method: 'DELETE',
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve({
            statusCode: res.statusCode,
            objectKey: objectKey,
            deleted: true
          });
        } else {
          reject(new Error(`删除对象失败: HTTP ${res.statusCode}`));
        }
      },
      fail: (error) => {
        reject(error);
      }
    });
  });
}

/**
 * 上传图片
 * @param {Object} options - 上传选项
 * @returns {void}
 */
function uploadImage(options) {
  const {
    chooseImage = wx.chooseImage,
    success,
    fail,
    prefix = 'images/'
  } = options;
  
  chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      
      // 生成随机文件名
      const timestamp = Date.now();
      const randomStr = Math.random().toString(36).substring(2, 8);
      const extension = tempFilePath.substring(tempFilePath.lastIndexOf('.') + 1);
      const objectKey = `${prefix}${timestamp}-${randomStr}.${extension}`;
      
      uploadFile(
        tempFilePath,
        objectKey,
        `image/${extension === 'jpg' ? 'jpeg' : extension}`
      )
      .then((result) => {
        if (success) {
          success({
            imageUrl: result.url,
            objectKey: result.objectKey
          });
        }
      })
      .catch((error) => {
        console.error('上传图片失败:', error);
        if (fail) {
          fail(error);
        }
      });
    },
    fail: (error) => {
      console.error('选择图片失败:', error);
      if (fail) {
        fail(error);
      }
    }
  });
}

module.exports = {
  getObjectURL,
  uploadFile,
  downloadFile,
  getObjectInfo,
  deleteObject,
  uploadImage
}; 